<template>
  <page-layout>
    <!-- 列表页面 -->
    <a-row :gutter="[10, 10]">
      <!-- 查询条件 -->
      <a-col :span="24">
        <a-card>
          <pro-query
            :searchParam="searchParam"
            @on-search ="search"
          >
            <template #test="{ data }">
              <a-input v-model:value="data.test" type="text" />
            </template>
          </pro-query>
        </a-card>
      </a-col>
      <!-- 用户列表 -->
      <a-col :span="24">
        <a-card>
          <pro-table
            ref="tableRef"
            :fetch="fetch"
            :columns="columns"
            :toolbar="toolbar"
            :operate="operate"
            :param="state.param"
            :pagination="pagination"
            :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }">
          </pro-table>
        </a-card>
      </a-col>
    </a-row>
    <!-- 新增页面 -->
    <save :visible="state.visibleSave" @close="closeSave" :record="state.record"></save>
    <!-- 修改页面 -->
    <edit :visible="state.visibleEdit" @close="closeEdit" :record="state.recordEdit" ></edit>
    <!-- 详情页面 -->
    <info :visible="state.visibleInfo" @close="closeInfo" :record="state.recordInfo"></info>
  </page-layout>
</template>

<script>
import save from './modal/save';
import edit from './modal/edit';
import info from './modal/info';
import {message, modal} from 'ant-design-vue';
import {ExclamationCircleOutlined} from '@ant-design/icons-vue';
import {deleteFiles, deleteResourcePermissionCheck, downloadDocument, page, remove} from "@/api/module/resource";
import {createVNode, reactive, ref} from 'vue';

const removeKey = "remove";
const removeBatchKey = "removeBatch";

export default {

  components: {
    save,
    edit,
    info,
  },
  setup() {
    const tableRef = ref();
    let isResourcePermissionCheck;

    /// 查询用户
    const fetch = async (param) => {
      const response = await page(param);
      return {
        total: response.data.total,
        data: response.data.record,
      };
    };


    function base64Encode(str) {
      const base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
      const base64DecodeChars = new Array(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);

      var out, i, len;
      var c1, c2, c3;
      len = str.length;
      i = 0;
      out = "";
      while (i < len) {
        c1 = str.charCodeAt(i++) & 0xff;
        if (i == len) {
          out += base64EncodeChars.charAt(c1 >> 2);
          out += base64EncodeChars.charAt((c1 & 0x3) << 4);
          out += "==";
          break;
        }
        c2 = str.charCodeAt(i++);
        if (i == len) {
          out += base64EncodeChars.charAt(c1 >> 2);
          out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
          out += base64EncodeChars.charAt((c2 & 0xF) << 2);
          out += "=";
          break;
        }
        c3 = str.charCodeAt(i++);
        out += base64EncodeChars.charAt(c1 >> 2);
        out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
        out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
        out += base64EncodeChars.charAt(c3 & 0x3F);
      }
      return out;
    }
    // 查看预览
    function checkMethod(record) {
      // var url = 'http://127.0.0.1:8080/file/test.txt'; //要预览文件的访问地址
      window.open('http://192.168.0.145:8012/onlinePreview?url='+encodeURIComponent(base64Encode(record.reAddress)));
    }

    /// 删除资源
    const removeMethod = async (record) => {
      await resourcePermissionCheck(record.reUploader)
      //逻辑是 只有上传者可以修改和删除，其他人只有查看的权限
      if(isResourcePermissionCheck){
        // 当 isResourcePermissionCheck 为true得时候说明该资源是当前登陆人创建的，可以修改或者删除
        modal.confirm({
          title: '您是否要删除该文件？',
          icon: createVNode(ExclamationCircleOutlined),
          okText: '确定',
          cancelText: '取消',
          onOk() {
            message.loading({ content: "提交中...", key: removeKey });
            remove({"id":record.reId}).then((response) => {
              if(response.success){
                deleteFiles(record.reAddress).then((response) => {
                })
                message.success({content: "删除成功", key: removeKey, duration: 1}).then(() =>
                  tableRef.value.reload()
                )
              }else{
                message.error({content: "删除失败", key: removeKey, duration: 1})
              }
            })
          }
        });
      }else {
        message.error("您没有权限删除其他用户所拥有的资源")
      }
    }

    // 修改资源
      const updateMethod = async (record) => {
        await resourcePermissionCheck(record.reUploader)
      //逻辑是 只有上传者可以修改和删除，其他人只有查看的权限
        if(isResourcePermissionCheck){
          state.visibleEdit = true
          state.recordEdit = record
          // 当 isResourcePermissionCheck 为true得时候说明该资源是当前登陆人创建的，可以修改或者删除
        }else {
          message.error("您没有权限修改其他用户所拥有的资源")
        }

    }

    // 下载
    const downloadMethod = async (record) =>{
      await resourcePermissionCheck(record.reUploader)
      //逻辑是 只有上传者可以修改和删除，其他人只有查看的权限
      if(isResourcePermissionCheck){
        // 当 isResourcePermissionCheck 为true得时候说明该资源是当前登陆人创建的，可以修改或者删除
        // downloadDocument({folderPath:record.reAddress}).then((response) => {
        // })
        window.location.href = encodeURI(process.env.VUE_APP_API_BASE_URL + '/api/sys/upload/downloadDocument?folderPath=' + record.reAddress)
      }else {
        message.error("您没有权限下载其他用户所拥有的资源")
      }
    };


    /// 工具栏
    const toolbar = [
      { label: "新增", event: function () { state.visibleSave = true }},
      // { label: "导出", event: function () { exportUserExcel(this.state); }},
      // { label: "删除", event: function () { removeBatchMethod(state.selectedRowKeys) }}
    ];
    // 删除资源权限校验
    const resourcePermissionCheck = async (data) =>{
      await  deleteResourcePermissionCheck(data).then((response) => {
        if(response.code === 500){
          isResourcePermissionCheck = false
        }else {
          isResourcePermissionCheck=( !!response.success);
        }
      })
    };


    /// 行操作
    const operate = [
      { label: "查看", event: function (record) { checkMethod(record) }},
      { label: "修改", event: function (record) { updateMethod(record) }},
      { label: "删除", event: function (record) { removeMethod(record) }},
      { label: '下载', event: function (record) { downloadMethod(record) }}
    ];
    /// 配置
    const columns = [
      { dataIndex: "reName", key: "reName", title: "资源名称" },
      { dataIndex: "reType", key: "reType", title: "上传类型"},
      { dataIndex: "size", key: "size", title: "文件大小" },
      { dataIndex: "reDownloundCount", key: "reDownloundCount", title: "下载次数" },
      // { dataIndex: "downloadableOrNot", key: "downloadableOrNot", title: "是否可下载", conver: converFormat},
      // { dataIndex: "reModule", key: "reModule", title: "模块" },
      { dataIndex: "reUploaderName", key: "reUploaderName", title: "上传者" },
      { dataIndex: "createTime", key: "createTime", title: "创建时间" }
    ];

    /// 分页参数
    const pagination = { pageNum: 1, pageSize: 10}

    /// 外置参数
    const state = reactive({
      selectedRowKeys: [],
      param: {},
      record: {},
      visibleSave: false,
      visibleEdit: false,
      visibleInfo: false,
      recordEdit: {},
      recordInfo: {},
    })
    /// 查询参数
    const searchParam = [
      { key: "name", type: "input", label: "资源名称"},
      // { key: "state", type: "select", label: "上传类型", value: "",
      //   options: [
      //     { text: "全部", value: ""},
      //     { text: "成功", value: true},
      //     { text: "失败", value: false}
      //   ]
      // },
      { key: "code", type: "input", label: "描述"},
    ]

    /// 选择操作
    const onSelectChange = selectedRowKeys => {
      state.selectedRowKeys = selectedRowKeys;
    };

    /// 查询操作
    const search = function(value) {
      state.param = value;
      tableRef.value.reload();
    }

    /// 关闭新增
    const closeSave = function(){
      state.visibleSave = false;
      tableRef.value.reload();
    }

    /// 关闭修改
    const closeEdit = function(){
      state.visibleEdit = false;
      tableRef.value.reload();
    }


    /// 关闭详情
    const closeInfo = function(){
      state.visibleInfo = false;
    }


    return {
      state,
      fetch,
      search,
      toolbar,
      columns,
      operate,
      pagination,
      searchParam,
      onSelectChange,

      closeSave,
      closeEdit,
      closeInfo,

      tableRef
    };
  },
};
</script>
